<?php


namespace App\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class SmsService
{
    const KEY = 'LTAI5tJ4PNAoqt7Qervpj8XX';
    const SECRET = 'MsrAGE20pEEN76Hl8AeWy2Ruqv2g59';
    const SIGN = '翼来电';

    /**
     * 使用AK&SK初始化账号Client
     * @param mixed $accessKeyId
     * @param mixed $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId = null, $accessKeySecret = null)
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId ?? SmsService::KEY,
            "accessKeySecret" => $accessKeySecret ?? SmsService::SECRET
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**登陆验证码
     * @param int $phone
     * @param array $paramsArray
     * @param string $templateCode
     * @return array|int[]
     */
    public static function sendSms(int $phone, array $paramsArray, string $templateCode = ''):array
    {
        $client = self::createClient(SmsService::KEY, SmsService::SECRET);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => SmsService::SIGN,
            "templateCode" => $templateCode,//这里是短信的模板id
            "templateParam" => json_encode($paramsArray)
        ]);
        $result = $client->sendSms($sendSmsRequest);
        if ($result->body->message == 'OK' && $result->body->code == 'OK') {
            return ['status' => 1];
        }
        if ($result->body->code == 'isv.MOBILE_NUMBER_ILLEGAL') {
            return ['status' => 0, 'msg' => '手机号码格式不正确'];
        }
        return ['status' => 0, 'msg' => '短信发送失败，网络繁忙'];
    }
}
